<?php
	header('content-type:text/html;charset=utf-8');
	date_default_timezone_set("Asia/Chongqing");
	require('../config/config.php');
	require('../class/function.php');
	require('../class/autoload.php');
	session_start();


	//判断是否为微信浏览器
	// if(!CheckMicroBrowser()){
	// 	exit('10007');
	// }


	//判断来路域名是否合法
    if(!CheckOrignDomain()){
    	exit('10001');
    }

	//判断来路路径是否在合法路径集中
	if(!CheckReferer()){
		exit('10002');
	}

	$openid = I('openid','p');
	$token1 = I('token1','p');

	if($_REQUEST['type'] != 'login'){
		if(!$openid || !$token1){
			exit('10004');
		}
		
		$db_host = trim(@$_POST['token2']);
		$db_name = trim(@$_POST['token3']);
		$city_code = trim(@$_POST['token4']);
		if(!$openid || !$token1 || !$db_host || !$db_name || !$city_code){
			if($_REQUEST['type'] != 'get_open_city'){ 
				exit('10005');	//缺少必要参数
			}
		}

		//检测token1
		$token3 = VerifyToken1($openid,$token1,1);
		if(!$token3){
			//exit('10006');		//token1 验证失败
		}
		$tmp_arr = array(
			'token1'=>$token3
		);
	}

	switch ($_REQUEST['type']) {

		//罢免超管申请
		case 'dismissAdmin':
			$adminOpenid = I('adminOpenid','p');
			$openid = I('openid','p');
			$area_id = intval(I('area_id','p'));
			if(!$adminOpenid || !$openid || !$area_id){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$pdo = MyPdoCounty::init();
			$sql = 'select id from super_admin_dis where area_id = ? and admin_openid = ? limit 1';
			$res = $pdo->dql($sql,array($area_id,$adminOpenid));
			if($res){
				$tmp_arr['stat'] = 'err2';	//不得重复申请
				exit(json_encode($tmp_arr));
			}
			$sql2 = 'insert into super_admin_dis values(null,?,?,?)';
			$res2 = $pdo->dml($sql2,array($area_id,$adminOpenid,$openid));
			if($res2){
				$tmp_arr['stat'] = 'ok';
			}else{
				$tmp_arr['stat'] = 'err3';	//操作异常
			}
			exit(json_encode($tmp_arr));
			break;





		//检测超管申请
		case 'checkSuperAdminVote':
			$area_id = intval(I('area_id','p'));
			if(!$area_id){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$pdo = MyPdoCounty::init();
			$sql = 'select id from super_admin_record where area_id = ? limit 1';
			$res = $pdo->dql($sql,array($area_id));
			if($res){
				$tmp_arr['stat'] = 'have';	//有超管申请
			}else{
				$sql2 = 'select id from super_admin_dis where area_id = ? limit 1';
				$res2 = $pdo->dql($sql2,array($area_id));
				if($res2){
					$tmp_arr['stat'] = 'have';	//有超管申请
				}else{
					$tmp_arr['stat'] = 'no';
				}
			}
			exit(json_encode($tmp_arr));
			break;


		//给申请超管的用户投票
		case 'addTicket':

			$admin_openid = I('admin_openid','p');
			$area_id = intval(I('area_id','p'));
			if(!$admin_openid || !$area_id){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$pdo = MyPdoCounty::init();
			
			//检测投票用户是否已投过票
			$sql = 'select id from super_admin_record where area_id = ? and user_openid = ?';
			$res = $pdo->dql($sql,array($area_id,$openid));
			if($res){
				$tmp_arr['stat'] = 'err2';	//已投过票了
			}else{
				$sql2 = 'insert into super_admin_record values(null,?,?,?)';
				$res2 = $pdo->dml($sql2,array($area_id,$admin_openid,$openid));
				if($res2){
					$tmp_arr['stat'] = 'ok';
					//投票成功后，获取小区总人数，及投票人总数
					$sql4 = 'select admin_openid,count(admin_openid) ac from super_admin_record where area_id = ? group by admin_openid';
					//获取到投票总数
					$resVote = $pdo->dql($sql4,array($area_id));
					if($resVote){	
						//获取小区总人数
						$sql3 = 'select count(id) uc from area_users_list where area_id = ?';
						$res3 = $pdo->dql($sql3,array($area_id),1);
						if($res3){	//获取到小区总人数
							//dump($res3);
							$areaCount = $res3['uc'];	//小区总人数
							$voteCount = 0;
							$baseOpenid = '';
							$baseCount = 0;
							foreach($resVote as $v){
								if($v['ac'] > $baseCount){
									$baseOpenid = $v['admin_openid'];
									$baseCount = $v['ac'];
								}
								$voteCount += $v['ac'];
							}
							//echo $voteCount.'---'.$areaCount;
							if($voteCount*2 > $areaCount){//投票人数大于半数
								//更改小区超管
								$changeAdminSql = 'update area_users_list set level=1 where area_id = ? and openid = ?';
								$changeAdminRes = $pdo->dml($changeAdminSql,array($area_id,$baseOpenid));
								if($changeAdminRes){
									//清空超申请表相关数据
									$clearVoteSql = 'delete from super_admin_record where area_id = ?';
									$clearVoteRes = $pdo->dml($clearVoteSql,array($area_id));
									if($clearVoteRes){
										$tmp_arr['stat'] = 'ok2';	//请求异常
									}
								}
							}
						}
					}
				}else{
					$tmp_arr['stat'] = 'err3';	//请求异常
				}
			}
			exit(json_encode($tmp_arr));
			break;



		//退出小区
		case 'exitArea':
			$area_id = intval(I('area_id','p'));
			if(!$area_id){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$pdo = MyPdoCounty::init();
			//删除小区用户中记录
			$sql1 = 'delete from area_users_list where area_id = ? and openid = ?';
			$res1 = $pdo->dml($sql1,array($area_id,$openid));
			//删除
			$sql2 = 'delete from my_area_list where area_id = ? and openid = ?';
			$res2 = $pdo->dml($sql2,array($area_id,$openid));
			$tmp_arr['stat'] = 'ok';	//缺少参数
			exit(json_encode($tmp_arr));
			break;




		//获取投票数
		case 'getTicket':
			$msg_id = intval(I('msg_id','p'));
			$area_id = intval(I('area_id','p'));
			if(!$msg_id || !$area_id){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$pdo = MyPdoCounty::init();
			$sql = 'select type,count(type) as count from area_msg_vote where msg_id = ? and area_id = ? group by type';
			$res = $pdo->dql($sql,array($msg_id,$area_id));
			if($res){
				$tmp_arr['data'] = $res;	//缺少参数
			}else{
				$tmp_arr['data'] = array();	//缺少参数
			}
			exit(json_encode($tmp_arr));
			break;



		//投票操作
		case 'favorOrOppose':
			$ctype = I('ctype','p')=='favor'?'favor':'oppose';
			$msg_id = I('msg_id','p');
			$area_id = I('area_id','p');
			if(!$msg_id || !$area_id || !$ctype){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$pdo = MyPdoCounty::init();
			$sql2 = 'select id from area_msg_vote where msg_id = ? and area_id = ? and openid = ?';
			$res2 = $pdo->dql($sql2,array($msg_id,$area_id,$openid),1);
			if($res2){
				$tmp_arr['stat'] = 'err2';	//已投过票了
			}else{
				$sql = 'insert into area_msg_vote values(null,?,?,?,?)';
				$res = $pdo->dml($sql,array($msg_id,$area_id,$openid,$ctype));
				if($res){
					$tmp_arr['stat'] = 'ok';	//投票成功
				}else{
					$tmp_arr['stat'] = 'err3';	//投票异常
				}
			}
			exit(json_encode($tmp_arr));
			break;


		//获取超管任免申请信息
		case 'getSuperAdminRegisterList':
			$area_id = intval(I('area_id','p'));
			if(!$area_id){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$pdo = MyPdoCounty::init();
			$sql = 'select admin_openid,count(user_openid) as count from super_admin_record where area_id = ? group by admin_openid';
			$res = $pdo->dql($sql,array($area_id));
			if($res){	//有申请超管数据
				$tmp_arr['data'] = $res;
				$tmp_arr['type'] = 'apply';	//任免类型：申请超管
			}else{
				$sql2 = 'select admin_openid,count(user_openid) as count from super_admin_dis where area_id = ? group by admin_openid';
				$res2 = $pdo->dql($sql2,array($area_id));
				if($res2){
					$tmp_arr['data'] = $res2;	//缺少参数
					$tmp_arr['type'] = 'dis';	//任免类型：罢免超管
				}else{
					$tmp_arr['data'] = array();	//缺少参数
				}
			}
			exit(json_encode($tmp_arr));
			break;



		//获取小区指定信息详情
		case 'GetMsg':
			$area_id = intval(I('area_id','p'));
			$msg_id = intval(I('msg_id','p'));
			if(!$area_id || !$msg_id){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$pdo = MyPdoCounty::init();
			$sql = 'select id,openid,info_title,info_content,type,time from area_msg_list where id = ? and area_id = ? and stat = 3';
			$res = $pdo->dql($sql,array($msg_id,$area_id),1);
			if($res){
				$tmp_arr['stat'] = 'ok';
				$tmp_arr['data'] = $res;
			}else{
				$tmp_arr['stat'] = 'err2';	//信息不存在
			}
			exit(json_encode($tmp_arr));
			break;


		//获取小区信息列表
		case 'GetAreaInfoList':
			$area_id = intval(I('area_id','p'));
			$pnow = intval(I('pnow','p'))?intval(I('pnow','p')):1;
			if(!$area_id){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$limit = 5;
			$limit_start = ($pnow-1)*$limit;
			$pdo = MyPdoCounty::init();
			$sql = "select id,openid,info_title,time from area_msg_list where area_id = ? and stat = 3 order by id desc limit {$limit_start},{$limit}";
			$res = $pdo->dql($sql,array($area_id));
			$tmp_arr['stat'] = 'ok';
			if($res){
				$tmp_arr['data'] = $res;
			}else{
				$tmp_arr['data'] = array();
			}
			exit(json_encode($tmp_arr));
			break;



		//发布小区信息
		case 'issue_info':
			$area_id = intval(I('area_id','p'));
			$title = I('title','p');
			$info = I('info','p');
			$rtype = I('rtype','p');
			if(!$area_id || !$title || !$info || !$rtype){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$pdo = MyPdoCounty::init();
			$tag_time = GetDateYmd(-1);
			$sql2 = 'select count(id) as c from area_msg_list where area_id = ? and time > ? limit 1';
			$res2 = $pdo->dql($sql2,array($area_id,$tag_time),1);
			if($res2 && $res2['c'] > 104){
				$tmp_arr['stat'] = 'err2';	//每天发布信息不得超过5条
			}else{
				$sql = 'insert into area_msg_list values(null,?,?,?,?,?,?,?,3)';
				$res = $pdo->dml($sql,array($openid,$area_id,$city_code,$title,$info,$rtype,time()));
				if($res){
					$tmp_arr['stat'] = 'ok';
				}else{
					$tmp_arr['stat'] = 'err3';
				}
			}
			exit(json_encode($tmp_arr));
			break;




		//撤消普管
		case 'cancelAdmin':
			$adminOpenid = I('adminOpenid','p');
			$area_id = I('area_id','p');
			if(!$adminOpenid){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$pdo = MyPdoCounty::init();
			$sql = 'update area_users_list set level = 3 where area_id = ? and openid = ?';
			$res = $pdo->dml($sql,array($area_id,$adminOpenid));
			if($res){
				$tmp_arr['stat'] = 'ok';
			}else{
				$tmp_arr['stat'] = 'err2';
			}
			exit(json_encode($tmp_arr));
			break;










		//转让超管
		case 'transAdmin':
			$area_id = intval(I('area_id','p'));
			$numb = intval(I('numb','p'));
			if(!$area_id || !$numb){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$changeOpenid = 'omTFa02CiCTgB5FqQ4cHDcI7txXA'.$numb;
			$pdo = MyPdoCounty::init();
			//自己降级
			$sql = 'update area_users_list set level=2 where area_id = ? and openid = ?';
			$res = $pdo->dml($sql,array($area_id,$openid));
			if($res){
				//转让指定用户
				$sql2 = 'select id from area_users_list where openid = ? and area_id = ? and level != 1';
				$res2 = $pdo->dql($sql2,array($changeOpenid,$area_id));
				if($res2){	//有则更改
					$sql3 = 'update area_users_list set level = 1 where area_id=? and openid = ?';
					$res3 = $pdo->dml($sql3,array($area_id,$changeOpenid));
					if($res3){
						$tmp_arr['stat'] = 'ok';
					}else{
						$tmp_arr['stat'] = 'err4';
					}
				}else{		//无则添加
					$sql4 = 'insert into area_users_list values(null,?,?,1,1,1,1)';
					$res4 = $pdo->dml($sql4,array($area_id,$changeOpenid));
					if($res4){
						$tmp_arr['stat'] = 'ok';
					}else{
						$tmp_arr['stat'] = 'err3';
					}
				}
			}else{
				$tmp_arr['stat'] = 'err2';	//缺少必要参数
			}
			exit(json_encode($tmp_arr));

			break;






		//撤消，转让超管
		case 'ChangePrem':
			$ctype = I('ctype','p');	//1转让超管 2撤消普管 3罢免超管
			$user_id = I('user_id','p');
			$area_id = I('area_id','p');
			$numb = I('numb','p');
			if(!$ctype || !$user_id || !$area_id){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$pdo = MyPdoCounty::init();
				$sql = "update area_users_list set level = 3 where area_id = ? and id = ?";
				$res = $pdo->dml($sql,array($area_id,$user_id));
				if($res){
					$tmp_arr['stat'] = 'ok';	
				}else{
					$tmp_arr['stat'] = 'err2';	
				}
				exit(json_encode($tmp_arr));
			if($ctype == 2){	//撤消管理
			}else{				//转让超管

			}
			break;



		//申请超管
		case 'ApplyLeader':
			$area_id = intval(I('area_id','p'));
			if(!$area_id){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}

			$pdo = MyPdoCounty::init();
			//检测是否有正常状态的超管存在
			$sql = 'select id from area_users_list where area_id = ? and stat = 1 and level = 1';
			$res = $pdo->dql($sql,array($area_id));
			if($res){
				$tmp_arr['stat'] = 'err2';	//存在超管，不能申请
				exit(json_encode($tmp_arr));
			}
			$sql2 = 'select id from super_admin_record where area_id = ? and admin_openid = ?';
			$res2 = $pdo->dql($sql2,array($area_id,$openid),1);
			if($res2){
				$tmp_arr['stat'] = 'err2';	//不能重复申请
				exit(json_encode($tmp_arr));
			}
			$sql3 = 'insert into super_admin_record values(null,?,?,?)';
			$res3 = $pdo->dml($sql3,array($area_id,$openid,$openid));
			if($res3){
				$tmp_arr['stat'] = 'ok';
			}else{
				$tmp_arr['stat'] = 'err3';	//请求失败
			}
			exit(json_encode($tmp_arr));
			break;



		//获取小区的管理员列表
		case 'GetAdminUserList':
			$area_id = intval(I('area_id','p'));
			if(!$area_id){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}
			$pdo = MyPdoCounty::init();
			$sql = 'select id,openid,level from area_users_list where area_id = ? and stat = 1 and level != 3';
			$res = $pdo->dql($sql,array($area_id));
			if($res){
				$tmp_arr['stat'] = 'ok';
				$tmp_arr['data'] = $res;
			}else{
				$tmp_arr['stat'] = 'err2';
			}
			exit(json_encode($tmp_arr));
			break;




		//加入小区
		case 'join_area':
			$area_id = I('area_id','p');
			$pwd = I('pwd','p');
			if(!$area_id || !$pwd){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}

			$pdo = MyPdoCounty::init();

			$join_my_stat = false;
			//添加到我的小区列表
			$sql = 'select area_id_list from my_area_list where openid = ?';
			$res = $pdo->dql($sql,array($openid),1);
			if(@$res && $res['area_id_list']){	//有则追加
				$ids = explode(',',$res['area_id_list']);
				if(!in_array($area_id,$ids)){ //不存在则添加
					array_push($ids,$area_id);
					$ids_str = implode($ids,',');
					$sqlmy = 'update my_area_list set area_id_list = ? where openid = ?';
					$resmy = $pdo->dml($sqlmy,array($ids_str,$openid));
				}
			}else{
				$join_my_stat = true; //不存在则添加
				$sqlmy = 'insert into my_area_list values(?,?)';
				$resmy = $pdo->dml($sqlmy,array($openid,$area_id));
			}


			
			//添加到小区用户列表
			$sql2 = 'select stat from area_users_list where area_id = ? and openid = ?';
			$res2 = $pdo->dql($sql2,array($area_id,$openid),1);
			if(!$res2){
				$sqlarea = 'insert into area_users_list values(null,?,?,3,1,1,1)';
				$resarea = $pdo->dml($sqlarea,array($area_id,$openid));
			}

		
			$tmp_arr['stat'] = 'ok';	//缺少参数
			exit(json_encode($tmp_arr));
			break;



		//获取城市小区列表
		case 'GetCityAreaList':
			$pnow = intval(@$_POST['pnow'])?:1;

			$limit = 10;
			$limit_start = ($pnow-1) * $limit;

			$pdo = MyPdoCounty::init();
			$sql = "select id,area_name,pwd from area_list where city_code = ? and stat = 2 limit {$limit_start},{$limit}";
			$res = $pdo->dql($sql,array($city_code));
			$tmp_data = array(
				'time'=>time()*1000
			);
			if($res){
				$tmp_data['data'] = $res;
			}else{
				$tmp_data['data'] = array();
			}
			$tmp_arr['data'] = $tmp_data;

			$path = '/CityAreaList/'.$city_code.'/'.$pnow.'.html';
			ToSaveData($path,json_encode($tmp_arr['data']),$config);
			exit(json_encode($tmp_arr));
			break;


		//获取我的小区id列表
		case 'GetMyAreaList':
			$pdo = MyPdoCounty::init();
			//$sql = 'select id,area_name,stat,openid from area_list where id in (select area_id from my_area_list where openid = ?) and city_code = ?';
			$sql = 'select area_id_list from my_area_list where openid = ?';
			$res = $pdo->dql($sql,array($openid),1);
			if($res){
				$tmp_arr['data'] = $res;
			}else{
				$tmp_arr['data'] = array();
			}
			exit(json_encode($tmp_arr));
			break;




		//创建小区
		case 'create_area';
			$area_name = trim(@$_POST['area_name']);
			if(!$area_name){
				$tmp_arr['stat'] = 'err1';	//缺少参数
				exit(json_encode($tmp_arr));
			}

			$path = '/area_stat/'.$city_code.'/'.$area_name.'.html';	//缓存小区状态的路径(本地或upyun)

			$pdo = MyPdoCounty::init();

			//检测创建个数
			$sql_c = 'select count(*) as c from area_list where city_code = ? and openid=?';
			$res_c = $pdo->dql($sql_c,array($city_code,$openid),1);
			if($res_c['c'] >= $config['create_area_limit']){
				$tmp_arr['stat'] = 'err7';	//成功
				exit(json_encode($tmp_arr));
			}

			$sql = 'select stat from area_list where city_code = ? and area_name = ?';
			$res = $pdo->dql($sql,array($city_code,$area_name),1);
			if(!$res){	
				//创建小区
				$sql2 = 'insert into area_list values(null,?,?,1,?,?)';
				$new_id = $pdo->dml($sql2,array($city_code,$area_name,$openid,rand(1000,9999)));
				if($new_id){
					$sql3 = 'insert into my_area_list values(?,?)';	//添加到我的小区列表
					$res3 = $pdo->dml($sql3,array($openid,$new_id));
					if($res3){
						//添加到小区用户列表
						$sql5 = 'insert into area_users_list values(?,?,1,1,1,1)';
						$res5 = $pdo->dml($sql5,array($new_id,$openid));
						if($res5){
							$tmp_arr['stat'] = 'ok';	//成功
						}else{
							$tmp_arr['stat'] = 'err6';	//添加到小区用户列表失败
						}
						ToSaveData($path,1,$config);
					}else{
						//添加到我的小区列表失败,需要删除创建的小区
						$sql4 = 'delete from area_list where id = ?';
						$res4 = $pdo->dml($sql4,array($new_id));
						$tmp_arr['stat'] = 'err5';	//添加出现异常
					}
				}else{
					$tmp_arr['stat'] = 'err4';	//添加失败
				}
			}else{
				$tmp_arr['stat'] = $res['stat'];	//小区存在 ，返回小区状态
				ToSaveData($path,$tmp_arr['stat'],$config);
			}
			exit(json_encode($tmp_arr));
			break;



		//获取开通的城市列表
		case 'get_open_city':
			//限制短时频繁请求
			$shortLimitTime = 1;
			$recoverfile = '../cache/tmp/openCity_time_limit';
			if(S($recoverfile)){
				$t1 = intval(S($recoverfile));
				if($t1 > time()){
					exit;
				}else{
					S($recoverfile,time()+$shortLimitTime);
				}
			}else{
				S($recoverfile,time()+$shortLimitTime);
			}
			$res = get_open_city($config);
			if($res){
				$tmp_arr['data'] = $res;
				exit(json_encode($tmp_arr));
			}
			break;




		//微信用户使用openid和ip获取token1
		case 'login':
			$token1 = SetToken1($openid,1);
			exit($token1);
			break;

		default :
			echo 'default';
			dump($_POST);
			break;






		
	}








